package com.gujiangbo.application.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

public class ContextHolder {
	private static Log debugLog = LogFactory.getLog(ContextHolder.class);
	@Autowired
	private static ApplicationContext ctx;

	public static ApplicationContext getCtx() {
		return ctx;
	}

	public static Object getBean(String beanName) {
		if (ctx != null) {
			try {
				return ctx.getBean(beanName);
			} catch (BeansException e) {
				debugLog.isErrorEnabled();
			}
		}
		if (debugLog.isDebugEnabled()) {
			debugLog.debug("Application context is null,bean=" + beanName);
		}
		return null;
	}

	public static Object getService(String servicename) {
		return getBean(servicename);
	}

	public static void setCtx(ApplicationContext context) {
		if (ctx == null) {
			ctx = context;
		}
	}

	public static String[] getBeanNamesForType(Class clazz) {
		if (ctx != null) {
			return ctx.getBeanNamesForType(clazz);
		}
		return new String[0];
	}

	public static void clearCtx() {
		if (ctx != null) {
			ctx = null;
		}
	}
}
